import { _decorator, Component, Node, Label, Sprite, Prefab, Input, EventTouch, EditBox, tween, v3 } from 'cc';
import { DataManager } from '../Public/DataManager';
import { PoolManager } from '../Public/PoolManager';
import { PublicFn } from '../Public/PublicFn';
const { ccclass, property } = _decorator;

@ccclass('Area')
export class Area extends Component {
    @property([Node])
    nodeArr: Node[] = [];
    @property(Node)
    addNode: Node = null;
    @property(Node)
    addNode1: Node = null;
    @property(Label)
    tip: Label = null;
    @property(Node)
    DefaultNode: Node = null;
    @property([Label])
    LabelArr: Label[] = [];
    @property(Prefab)
    text: Prefab = null;
    @property(Prefab)
    areames: Prefab = null;
    @property([EditBox])
    editArr: EditBox[] = [];
    strArr: string[] = [];
    is_default: number = 0;
    start() {
        this.getAreaList();
    }

    update(deltaTime: number) {

    }
    /**返回主页 */
    BacktoMain() {
        this.node.setPosition(600, 0);
    }
    /**关闭添加地址 */
    ClosePage() {
        this.nodeArr[1].active = false;
    }
    /**打开添加地址 */
    OpenPage() {
        this.nodeArr[1].active = true;
    }
    /**打开选址 */
    addArea() {
        this.nodeArr[2].active = true;
        this.strArr = [];
        this.LabelArr.forEach((e) => {
            e.string = `请选择`;
        })
        PoolManager.Instance.putAllNode(this.addNode,`text`);
        this.getPlaces();
    }
    /**关闭选址 */
    closeArea() {
        this.nodeArr[2].active = false;
        let str='';
        this.strArr.forEach((e)=>
        {
            if(str.match(e))
            {
                return ;
            }
            else
            {
                str+=e;
            }
        })
        this.editArr[2].string = str;
    }
    /**查询3级地址 */
    getPlaces(id: string = '1') {
        let xhr = new XMLHttpRequest();
        xhr.open(`post`, `https://2857e2g653.imdo.co/index.php/tpp/placesGet`);
        xhr.setRequestHeader(`content-type`, `application/x-www-form-urlencoded`);
        xhr.setRequestHeader(`token`, `${DataManager.Instance.token}`);
        xhr.send(`parent_id=${id}`);
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4 && xhr.status === 200) {
                const { code, data } = JSON.parse(xhr.response)
                if (code == 200) {
                    console.log('省级 :>> ', data);
                    this.tip.string='请选择省级';
                    data.forEach((e) => {
                        const node = PoolManager.Instance.getNode(this.text, this.addNode, `text`);
                        node.getComponent(Label).string = `${e.cname}`;
                        node.name = `${e.places_id}`;
                        node.on(Input.EventType.TOUCH_END, this.clickText, this);
                    });
                    console.log('this.addNode',this.addNode)
                }
                else {
                    console.log('JSON.parse(xhr.response) :>> ', JSON.parse(xhr.response));
                }
            }
        }
    }
    /**3级选地址点击事件 */
    clickText(e: EventTouch) {
        let xhr = new XMLHttpRequest();
        xhr.open(`post`, `https://2857e2g653.imdo.co/index.php/tpp/placesGet`);
        xhr.setRequestHeader(`content-type`, `application/x-www-form-urlencoded`);
        xhr.setRequestHeader(`token`, `${DataManager.Instance.token}`);
        xhr.send(`parent_id=${e.target.name}`);
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4 && xhr.status === 200) {
                const { code, data } = JSON.parse(xhr.response)
                if (code == 200) {
                    console.log('data :>> ', data);
                    this.strArr.push(e.target.getComponent(Label).string);
                    switch (this.strArr.length) {
                        case 1:
                            this.tip.string='请选择市级'
                            break;
                        case 2:
                            this.tip.string='请选择县级'
                            break;
                        default:
                            break;
                    }
                    this.strArr.forEach((e, i) => {
                        this.LabelArr[i].string = e;
                    })
                    PoolManager.Instance.putAllNode(this.addNode,`text`);
                    data.forEach((e,i) => {
                        const node = PoolManager.Instance.getNode(this.text, this.addNode, `text`);
                        node.getComponent(Label).string = `${e.cname}`;
                        node.name = `${e.places_id}`;
                        node.on(Input.EventType.TOUCH_END, this.clickText, this);
                        // console.log('node',node);
                    })
                    if(!data.length)
                    {
                        this.closeArea();
                    }
                }
                else {
                    console.log('JSON.parse(xhr.response) :>> ', JSON.parse(xhr.response));
                }
            }
        }
    }
    /**新建地址 */
    postAreaMess() {
        let iscom = false;
        this.editArr.forEach((e) => {
            e.string ? iscom = true : iscom = false;
        })
        if (!iscom||this.editArr[1].string.length<11) {
            return;
        }
        let xhr = new XMLHttpRequest();
        xhr.open(`post`, `https://2857e2g653.imdo.co/index.php/tpp/addressSet`);
        xhr.setRequestHeader(`content-type`, `application/x-www-form-urlencoded`);
        xhr.setRequestHeader(`token`, `${DataManager.Instance.token}`);
        xhr.send(`name=${this.editArr[0].string}&phone=${this.editArr[1].string}&address=${this.editArr[2].string}${this.editArr[3].string}&is_default=${this.is_default}`);
        this.is_default = 0;
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4 && xhr.status === 200) {
                const { code, data } = JSON.parse(xhr.response)
                if (code == 200) {
                    console.log('data :>> ', data);
                    PoolManager.Instance.putAllNode(this.addNode1,`areames`)
                    this.getAreaList();
                }
                else {
                    console.log('JSON.parse(xhr.response) :>> ', JSON.parse(xhr.response));
                }
            }
        }
    }
    /**收获列表 */
    getAreaList() {
        let xhr = new XMLHttpRequest();
        xhr.open(`post`, `https://2857e2g653.imdo.co/index.php/tpp/addressGet`);
        xhr.setRequestHeader(`content-type`, `application/x-www-form-urlencoded`);
        xhr.setRequestHeader(`token`, `${DataManager.Instance.token}`);
        xhr.send(`name=${this.editArr[0].string}&phone=${this.editArr[1].string}&address=${this.editArr[2].string}${this.editArr[3].string}&is_default=${this.is_default}`);
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4 && xhr.status === 200) {
                const { code, data } = JSON.parse(xhr.response)
                if (code == 200) {
                    console.log('data :>> ', data);
                    data.forEach((e) => {
                        const node = PoolManager.Instance.getNode(this.areames, this.addNode1,`areames`);
                        node.getChildByName(`l2`).getComponent(Label).string = `${e.address}`;
                        node.getChildByName(`l3`).getComponent(Label).string = `${e.name}`;
                        node.getChildByName(`l4`).getComponent(Label).string = `${e.phone}`;
                        PublicFn.Instance.changeImg(e.is_default ? `imgs/选中` : `imgs/未选中`, node.getChildByName(`select`).getComponent(Sprite));
                        node['default'] = e.is_default;
                        node.getChildByName(`select`).on(Input.EventType.TOUCH_END, this.setDefault, this);
                        node.name = `${e.address_id}`;
                        e.is_default ? DataManager.Instance.address_id = e.address_id : null;
                    })
                }
                else {
                    console.log('JSON.parse(xhr.response) :>> ', JSON.parse(xhr.response));
                }
            }
        }
    }
    /**设置默认地址 */
    setDefault(e: EventTouch) {
        const node = e.target.parent;
        let xhr = new XMLHttpRequest();
        xhr.open(`post`, `https://2857e2g653.imdo.co/index.php/tpp/addressGet`);
        xhr.setRequestHeader(`content-type`, `application/x-www-form-urlencoded`);
        xhr.setRequestHeader(`token`, `${DataManager.Instance.token}`);
        xhr.send(`address_id=${node.name}&is_default=${Number(!node['default'])}`);
        console.log(' :>> ', `address_id=${node.name}&is_default=${Number(!node['default'])}`);
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4 && xhr.status === 200) {
                const { code, data } = JSON.parse(xhr.response)
                if (code == 200) {
                    console.log('data :>> ', data);
                }
                else {
                    console.log('JSON.parse(xhr.response) :>> ', JSON.parse(xhr.response));
                }
            }
        }
    }
    /**选为默认地址 */
    clickDefault() {
        this.is_default = Number(!this.is_default);
        if (this.is_default) {
            tween(this.DefaultNode.getChildByName('dian')).to(0.1,{position:v3(20)}).start();
            PublicFn.Instance.changeImg(`imgs/开`, this.DefaultNode.getComponent(Sprite));
        }
        else {
            tween(this.DefaultNode.getChildByName('dian')).to(0.1,{position:v3(-20)}).start();
            PublicFn.Instance.changeImg(`imgs/关`, this.DefaultNode.getComponent(Sprite));
        }
    }
    /**检查手机输入是否正确 */
    checkPhone(str:string,e:EditBox)
    {
        const arr=str.match(/\d+/g);
        if(arr)
        {
            let s1='';
            console.log('arr',Array.isArray(arr))
            arr.forEach((s)=>
            {
                s1+=s;
            })
            e.string=s1;
        }
        else
        {
            e.string='';
        }
    }
    setType(str,e:EditBox)
    {
        e.node.children[0].getComponent(Label).overflow=3
    }
}

